<template>
  <!-- 添加模板 -->
  <el-dialog  :visible.sync="show" class="jx-dialog" width="80%">
    <div slot="title" class="header-title">
      <span class="title-name">{{currentRow.serviceProductId ? '编辑套餐' : '添加套餐'}}</span>
    </div>
    <el-form ref="form" :model="currentRow" :rules="rules" label-width="100px" class="jx-form">
      <div class="jx-detail">
        <div class="detail-item" style="margin-bottom: 40px;">
          <div class="item_2">
            <div class="title">基本信息</div>
            <el-form-item label="套餐名称：" prop="serviceProductName">
              <el-input class="tel-value" v-model="currentRow.serviceProductName" :disabled="currentRow.serviceProductId" placeholder="请输入套餐名称"></el-input>
            </el-form-item>
            <el-form-item label="适用车系：" prop="suitCarSeries">
              <el-select class="tel-value" v-model="currentRow.suitCarSeries" placeholder="请选择" :disabled="currentRow.serviceProductId">
                <el-option v-for="(item,index) in suitCarSeries" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="报名条件：" prop="warehouse_num">
              <el-select class="tel-value" v-model="currentRow.item5" placeholder="请选择">
                <el-option label="不限" value="1"></el-option>
                <el-option label="其他" value="2"></el-option>
              </el-select>
            </el-form-item> -->
          </div>
          <div class="item_2">
            <div class="title">产品清单</div>
            <div class="list">
              <div class="right">
                <el-input class="tel-value" type="textarea" row="3" v-model="currentRow.serviceProductList" :disabled="currentRow.serviceProductId" placeholder="请输入产品清单"></el-input>
              </div>
            </div>
            <div class="title" style="margin-top: 35px;">服务说明</div>
            <div class="list" v-for="(item,index) in currentRow.serviceProductDesc" :key="index">
              <div class="right">
                <el-input class="tel-value" v-model="item.text" placeholder="请输入服务说明" :disabled="currentRow.serviceProductId"></el-input>
                <el-button type="text" size="small" @click="addInfo" v-if="!currentRow.serviceProductId">增加</el-button>
                <el-button v-if="(currentRow.serviceProductDesc.length != 1) && (!currentRow.serviceProductId)" type="text" size="small" @click="deleteInfo(index)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="detail-item" style="margin-bottom: 10px">
          <div class="jx-table" style="padding: 0;">
            <div class="title">
              产品编号
              <el-input style="width: 25%;" class="tel-value" v-model="params_list.no" :disabled="currentRow.serviceProductId" placeholder="请输入产品编号"></el-input>
              <!-- <el-autocomplete
                  class="inline-input"
                  v-model="state2"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  :trigger-on-focus="false"
                  @select="handleSelect"
                ></el-autocomplete> -->
              <el-button class="jx-btn" v-if="!currentRow.serviceProductId" type="primary" :loading="boo.isExport" @click="addOther">{{boo.isExport ? '请稍后……' : '添加'}}</el-button>
              <!-- <div class="add-new">
                <el-button class="jx-btn" type="primary" @click="addRow">新增一行</el-button>
              </div> -->
            </div>
            <el-table :data="list" border show-summary :summary-method="getSum" style="width: 100%" v-loading="boo.loading"  :show-summary="boo.showSum">
              <el-table-column type="index" label="序列" width="50" align="center">
              </el-table-column>
              <el-table-column prop="serviceProductName" label="产品名称" width="160" align="center" fixed>
                <template slot-scope="scope">
                  <span v-if="scope.row.serviceProductName">{{scope.row.serviceProductName}}</span>
                  <!-- <el-input v-else class="tel-value" v-model="params_list.name" placeholder="请输入产品名称"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="serviceProductImgUrl" label="产品图片" width="130" align="center" fixed>
                <template slot-scope="scope">
                  <img v-if="scope.row.serviceProductImgUrl" class="logo" :src="scope.row.serviceProductImgUrl"/>
                  <!-- <el-upload
                    v-else
                    class="avatar-uploader jx-uploader"
                    name="imgFile"
                    :headers="headers"
                    :action="`${$api.common.upload}?catalog=product_supplier`"
                    :show-file-list="false"
                    :on-success="handleSuccess">
                    <img v-if="(params_list.img != '') && (params_list.img)" :src="params_list.img" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload> -->
                </template>
              </el-table-column>
              <el-table-column prop="catalogName" label="关联类目" align="center" width="160">
                <template slot-scope="scope">
                  <span v-if="scope.row.catalogName">{{scope.row.catalogName}}</span>
                  <!-- <el-cascader
                    v-else
                    class="tel-value"
                    v-model="params_list.category"
                    :options="typelist"
                    :props="props"
                    @change="handleChange">
                  </el-cascader> -->
                </template>
              </el-table-column>
              <el-table-column prop="shopProductCatalog" label="产品类型" align="center" width="120">
                <template slot-scope="scope">
                  <span v-if="scope.row.shopProductCatalog">{{scope.row.shopProductCatalog}}</span>
                  <!-- <el-select v-else class="tel-value" v-model="params_list.type" placeholder="请选择">
                    <el-option label="服务" value="1"></el-option>
                    <el-option label="其他" value="2"></el-option>
                  </el-select> -->
                </template>
              </el-table-column>
              <el-table-column prop="serviceProductSpec" label="产品规格" align="center" width="130">
                <template slot-scope="scope">
                  <span v-if="scope.row.serviceProductSpec">{{scope.row.serviceProductSpec}}</span>
                  <!-- <el-input v-else class="tel-value" v-model="params_list.norm" placeholder="请输入规格"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="serviceProductPrice" label="原价价格（元）" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{scope.row.serviceProductPrice}}</span>
                  <!-- <span v-if="scope.row.serviceProductPrice">{{scope.row.serviceProductPrice}}</span>
                  <el-input v-else class="tel-value" v-model="params_list.OldPrice" placeholder="请输入原价价格" @blur="test"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="packagePrice" label="套餐价格（元）" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.subServiceProductPrice">{{scope.row.subServiceProductPrice}}</span>
                  <el-input v-else class="tel-value" @blur="appIsNum($event, '套餐价格')" v-model="scope.row.packagePrice" :disabled="currentRow.serviceProductId" placeholder="请输入套餐价格"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="memberPrice" label="会员价格（元）" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.subServiceProductVipPrice">{{scope.row.subServiceProductVipPrice}}</span>
                  <el-input v-else class="tel-value" @blur="appIsNum($event, '会员价格')" v-model="scope.row.memberPrice" :disabled="currentRow.serviceProductId" placeholder="请输入会员价格"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="shopSum" label="产品数量" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.subServiceProductAmount">{{scope.row.subServiceProductAmount}}</span>
                  <el-input v-else class="tel-value" @blur="appIsNum($event, '产品数量')" v-model="scope.row.shopSum" :disabled="currentRow.serviceProductId" placeholder="请输入产品数量"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="serviceProductPrice" label="采购价格" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.serviceProductPrice">{{scope.row.serviceProductPrice}}</span>
                  <el-input v-else class="tel-value" v-model="params_list.purchasePrice" :disabled="currentRow.serviceProductId" placeholder="请输入采购价格"></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="mechanismPrice" label="机构价格" align="center" width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.mechanismPrice">{{scope.row.mechanismPrice}}</span>
                  <el-input v-else class="tel-value" v-model="params_list.mechanismPrice" placeholder="请输入机构价格"></el-input>
                </template>
              </el-table-column> -->
              <!-- <el-table-column label="操作" width="120" align="center" fixed> -->
                <!-- <template slot-scope="scope"> -->
                  <!-- <el-button v-if="scope.row.type == ''" @click="editRow(scope.row)" type="text" size="small">保存</el-button>-->
                  <!-- <el-button v-if="scope.row.serviceProductId != ''" @click="deleteRow(scope.row)" type="text" size="small">编辑</el-button>  -->
                  <!-- <el-button v-if="scope.row.serviceProductId != ''" @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </div>
      </div> 
    </el-form>
    <div class="btn-container" v-if="!currentRow.serviceProductId">
      <el-button class="jx-btn" type="primary" :loading="boo.saveing" @click="submitRow('form')">生成产品</el-button>
    </div>
  </el-dialog>
</template>
<script>
	export default {
    props: {
      isopen: Boolean,
      item: Object,
    },
    computed: {
      show: {
        get() {
          return this.isopen
        },
        set() {
          this.close('icon')
        },
      },
      currentRow(){
        return this.item
      }
    },
    
		data() {
			return {
        https: {
          list: this.$api.product.supplylist,
          type: this.$api.setting.category.list,
          suitCarSeries: this.$api.setting.car.page,
        },
        boo: {
          saveing: false,
          isExport: false,
          showSum: true,
        },
        headers: {
          'admin-auth-token': localStorage.getItem('ms_token') || ''
        },
        other: {
          allRow: 1,
          OldPrice: '199.00',
          packagePrice: '199.00',
          memberPrice: '199.00',
          shopSum: '199.00',
          purchasePrice: '199.00',
        },
        list: '',
        params_list: {
          page: 1,
          size: 10,
          no: '',
          img: '',
          name: '',
          category: '',
          type: '',
          sort: '',
          norm: '',
          OldPrice: '',
          shop: [{
            packagePrice: '',
            memberPrice: '',
            shopSum: '',
          }],
          purchasePrice: '',
        },
        typelist: '', // 关联类目
        suitCarSeries: '', // 适用车系
        props: {
          expandTrigger: 'click', 
          value: 'catalogId',
          label: 'catalogName',
        },
        rules: {
          suitCarSeries: [{ required: true, message: '请选择适用车系', trigger: 'change' }],
          serviceProductName: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
        },
			}
		},
		mounted(){
      let _self = this
      _self.getList()
      _self.getType() // 获取关联类目
      _self.getCar() // 获取适用车系
    }, 
		methods: {
      getType(){
        let _self = this
        let success = (res)=>{
          res = res.data
          if(res.retCode == 1){
            _self.typelist = res.retObject
          }else{
            _self.$message.error(res.retMsg)
          }
        }
        _self.$axios.get(_self.https.type, {}, success) 
      },
      getCar(){
        let _self = this
        let success = (res)=>{
          res = res.data
          if(res.retCode == 1){
            _self.suitCarSeries = res.retObject
          }else{
            _self.$message.error(res.retMsg)
          }
        }
        _self.$axios.get(_self.https.suitCarSeries, {}, success) 
      },
      getList(){
        let _self = this
        let params = {
          serviceProductNo: _self.params_list.no,
        }
        _self.boo.loading = true
        let success = (res)=>{
          res = res.data
          if(res.retCode == 1){
            res.retObject.forEach(item=>{
              item.packagePrice = item.subServiceProductPrice || 0
              item.memberPrice = item.subServiceProductVipPrice || 0
              item.shopSum = item.subServiceProductAmount || 0
            })
            _self.list = [..._self.list, ...res.retObject]
            _self.boo.showSum = false;
            _self.$nextTick(()=>{
              _self.boo.showSum = true;
            })
          }else{
            _self.$message.error(res.retMsg)
          }
          _self.boo.loading = false
        }
        _self.$axios.get(_self.https.list.listPackage, params, success) 
      },
      addOther(){
        let _self = this
        _self.getList()
      },
      appIsNum(e, type){
        let _self = this
        let val = e.target.value || 0
        if(!_self.$reg.isNum(val)){
          if(!_self.$reg.isFloat(val)) return _self.$message.error(type+ ' 必须是数字')
        }
        if((type == '产品数量') && (_self.$reg.isFloat(val))) return _self.$message.error(type+ ' 必须是整数')
      },
      getSum(param){
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) return sums[index] = '合计';
          if(!data) return
          const values = data.map(item => parseFloat(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) return prev + curr; 
              prev;
            }, 0);
            sums[index];
          } else {
            sums[index] = '';
          }
        });
        return sums;
      },
      handleSuccess(res){
        let _self = this
        if(!res) return
        if(res.retCode == 1){
          _self.params_list.img = res.retObject.defaultImgDetail.path
          _self.params_list.logoImgId = res.retObject.imgId
        }else{
          _self.$message.error(res.retMsg)
        }
      },
      addInfo(){
        let _self = this
        _self.currentRow.serviceProductDesc.push({
          'text': ''
        })
      },
      deleteInfo(index){
        let _self = this
        _self.currentRow.serviceProductDesc.splice(index,1)
      },
      close(type){
        let _self = this
        _self.$emit('close', false, type)
      },
      addRow(){
        let _self = this
        _self.list.push({
          img: '',
          name: '',
          category: '',
          type: '',
          sort: '',
          norm: '',
          OldPrice: '',
          packagePrice: '',
          memberPrice: '',
          shopSum: '',
          purchasePrice: '',
          mechanismPrice: '',
        })
      },
      editRow(){
        let _self = this
        let params = {
          img: _self.params_list.img,
          name: _self.params_list.name,
          category: _self.params_list.category,
          type: _self.params_list.type,
          sort: _self.params_list.sort,
          norm: _self.params_list.norm,
          OldPrice: _self.params_list.OldPrice,
          packagePrice: _self.params_list.packagePrice,
          memberPrice: _self.params_list.memberPrice,
          shopSum: _self.params_list.shopSum,
          purchasePrice: _self.params_list.purchasePrice,
          mechanismPrice: _self.params_list.mechanismPrice,
        }
      },
      deleteRow(){},
      submitRow(formName){
        let _self = this
				this.$refs[formName].validate((vaild)=>{
					if(vaild){  
            if((_self.currentRow.serviceProductList == '') || (_self.currentRow.serviceProductList == undefined)) return _self.$message.error('请输入产品清单')
            if(_self.currentRow.serviceProductDesc[0].text == '') return _self.$message.error('请输入服务说明')
            if(_self.list.length == 0) return _self.$message.error('请添加产品')
            let list = []
            _self.list.forEach(item => {
              list.push({
                subServiceProductId: item.serviceProductId,
                subServiceProductAmount: item.shopSum,
                subServiceProductPrice: item.packagePrice,
                subServiceProductVipPrice: item.memberPrice,
              })
            })
            _self.boo.saveing = true
            let params = {
              subList: JSON.stringify(list),
              serviceProductName: _self.currentRow.serviceProductName,
              suitCarSeries: _self.currentRow.suitCarSeries,
              serviceProductList: _self.currentRow.serviceProductList,
              serviceProductDesc: JSON.stringify(_self.currentRow.serviceProductDesc),
            } 
            let success = (res)=>{
              res = res.data
              if(res.retCode == 1){
                _self.close('btn')
              }else{
                _self.$message.error(res.retMsg)
              }
              _self.boo.saveing = false
            }
            _self.$axios.body(_self.https.list.addPackage, params, success)   
					}else{
						return false
					}
				})
      }
    }
	}

</script>
<style scoped lang="sass">
  .jx-table
    width: 100%
    /deep/ .el-table__body td
      .cell
        height: auto
        line-height: auto
    .title
      padding-bottom: 0
      /deep/ .jx-btn.el-button
        padding: 0 25px
        span
          color: #fff
          margin: 0
    .el-table .cell
      .el-input--small, .el-textarea
        width: 95%
      .el-cascader, .el-select
        width: 100%
        /deep/ .el-input--small
          width: 95%
  .jx-detail .detail-item .list span
    width: 75px
  .jx-detail .detail-item .right
    .tel-value 
      width: 220px
</style>
